package com.reservation.controller;

import com.reservation.common.ApiResponse;
import com.reservation.dto.UserDTO;
import com.reservation.service.AuthService;
import com.reservation.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final AuthService authService;
    private final JwtUtil jwtUtil;

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/me")
    public ApiResponse<UserDTO> getCurrentUser(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return ApiResponse.error("未提供认证令牌");
            }

            if (!jwtUtil.validateToken(token)) {
                return ApiResponse.error("认证令牌无效");
            }

            String username = jwtUtil.getUsernameFromToken(token);
            UserDTO user = authService.getUserByUsername(username);
            return ApiResponse.success("获取用户信息成功", user);
        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            return ApiResponse.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public ApiResponse<UserDTO> getUserById(@PathVariable Long id) {
        try {
            UserDTO user = authService.getUserById(id);
            return ApiResponse.success("获取用户信息成功", user);
        } catch (Exception e) {
            log.error("获取用户信息失败: id={}", id, e);
            return ApiResponse.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 从请求中提取JWT Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
